<?php

namespace app\index\controller;

use app\model\Member;
use app\model\Sms;
use app\service\PlatFormFactory;
use think\exception\ValidateException;
use app\model\Users;
use app\model\UuidRelation;
use app\model\Openid;
use think\facade\Cache;
use think\facade\Db;
use think\response\Json;

class LoginController extends Base
{
    //用户登录
    public function index()
    {
        $data = only('username,password');

        if (empty($data['username'])) {
            throw new ValidateException('请输入用户名');
        }

        if (empty($data['password'])) {
            throw new ValidateException('请输入密码');
        }

        $ptype = input('post.ptype');
        $res = $this->checkLogin($data);

        if ($res) {
            $this->userInfo['uuid'] = $res['uuid'];
            $this->setToken($this->userInfo, $this->getToken());

            // Openid::create(['uniacid' => uniacid(), 'uuid' => $res['uuid'], 'ptype' => $ptype, 'openid' => getFans()['openid']]);
            // UuidRelation::create(['uniacid' => uniacid(), 'uuid' => $res['uuid'], 'uid' => UID()]);

            return $this->json(['msg' => '登录成功', 'data' => $res]);
        }
    }

    //验证登录
    private function checkLogin($data)
    {
        $where['username'] = $data['username'];
        $field = 'id,uniacid,uuid,uid,sid,title,username,password,salt,create_time,status';
        $info = Users::field($field)->where($where)->find();
        if ($info) {
            $info = $info->toArray();
            if ($info['password'] === pass_hash($data['password'], $info["salt"])) {
                unset($info['password']);
                unset($info["salt"]);

                if (empty($info['uuid'])) {
                    $info['uuid'] = uniqid(rand(1, 10000));
                    Users::where('id', $info['id'])->update(['uuid' => $info['uuid']]);
                }

                if (!($info['status'])) {
                    throw new ValidateException("该账户被禁用");
                }
            } else {
                throw new ValidateException("用户名或者密码不正确");
            }
        } else {
            throw new ValidateException("用户名不存在");
        }

        return $info;
    }

    /**
     * @param \app\service\PlatFormFactory $platFormFactory
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loginByMobile(PlatFormFactory $platFormFactory): Json
    {
        $platformObj = $platFormFactory->create();
        $phone = $platformObj->getPhoneNumber();
        // $member = Member::where('id', UID())->findOrFail();
        $phoneMember = Member::where('telephone', $phone)->find();
        if(!$phoneMember) {
            $salt = substr(md5(uniqid()), 8, 8);
            $phoneMember = Member::create([
                'uuid' => uniqid(rand(1, 10000)),
                'uniacid' => uniacid(),
                'salt' => $salt,
                'password' => pass_hash($phone, $salt),
                'telephone' => $phone,
                'username' => $phone,
                'category_id' => 0,
                'regdate' => time(),
                'nickname' => substr_replace($phone, '*****', 3, 5),
            ]);

            $this->registerUserByMember($phoneMember);
        }else{
            $phoneMember->save([
                'lastdate' => time(),
            ]);
        }

        return $this->json([
            'errno' => 0,
            'msg' => '登录成功',
            'data' => $this->loginSuccess($phoneMember->toArray())
        ]);
    }

    public function loginByPhone()
    {
        $phone = $this->request->param('phone');
        $code = $this->request->param('code');

        $cacheCode = Cache::get($phone . '_login');

        if ($cacheCode !== $code) {
            return $this->json(['errno' => 1, 'msg' => '验证码错误']);
        }

       /* $oldMember = Member::where('telephone', $phone)->find();

        if ($oldMember && $oldMember->getKey() != UID()) {
            return $this->json(['errno' => 1, 'msg' => '该手机号已注册']);
        }

        $member = Member::where('id', UID())->findOrFail();
        $member->telephone = $phone;
        $member->save();

        Cache::delete($phone . '_login');
        return $this->json(['msg' => '登录成功', 'data' => []]);
       */
        $phoneMember = Member::where('telephone', $phone)->find();
        if(!$phoneMember) {
            $salt = substr(md5(uniqid()), 8, 8);
            $phoneMember = Member::create([
                'uuid' => uniqid(rand(1, 10000)),
                'uniacid' => uniacid(),
                'salt' => $salt,
                'password' => pass_hash($phone, $salt),
                'telephone' => $phone,
                'username' => $phone,
                'category_id' => 0,
                'regdate' => time(),
                'nickname' => substr_replace($phone, '*****', 3, 5),
            ]);
            $this->registerUserByMember($phoneMember);
        }else{
            $phoneMember->save([
                'lastdate' => time(),
            ]);
        }

        return $this->json([
            'errno' => 0,
            'msg' => '登录成功',
            'data' => $this->loginSuccess($phoneMember->toArray())
        ]);

    }

    public function sendCode()
    {
        $phone = $this->request->param('phone');
        $type = $this->request->param('type');

        Sms::send_sms([
            'phone' => $phone,
            'param' => json_encode([
                'code' => $this->getCode($phone, $type)
            ])
        ]);

        return $this->json(['msg' => '发送成功']);
    }

    public function getCode($phone, $type)
    {
        $code = mt_rand(1000, 9999);

        Cache::set($phone . $type, $code, 60 * 10);

        return $code;
    }

    public function registerByPhone()
    {
        $phone = $this->request->param('phone');
        $password = $this->request->param('password');
        $code = $this->request->param('code');

        $cacheCode = Cache::get($phone . '_register');

        if ($cacheCode !== $code) {
            return $this->json(['errno' => 1, 'msg' => '验证码错误']);
        }

        $oldMember = Member::where('telephone', $phone)->findOrEmpty();

        if ($oldMember->getKey()) {
            return $this->json(['errno' => 1, 'msg' => '该手机号已注册']);
        }

        Db::startTrans();
        try {
            $oldMember->uuid = uniqid(rand(1, 10000));
            $oldMember->salt = substr(md5(uniqid()), 8, 8);
            $oldMember->password = pass_hash($password, $oldMember->salt);
            $oldMember->telephone = $phone;
            $oldMember->username = $phone;
            $oldMember->uniacid = uniacid();
            $oldMember->category_id = 0;
            $oldMember->regdate = time();
            $oldMember->nickname = $phone;
            $oldMember->save();

            Cache::delete($phone . '_register');

            $this->registerUserByMember($oldMember);

            Db::commit();
        } catch (\Throwable $throwable) {
            Db::rollback();
            return $this->json(['errno' => 1, 'msg' => $throwable->getMessage()]);
        }

        return $this->json(['msg' => '注册成功']);
    }

    public function loginByMobileH5()
    {
        $phone = $this->request->param('phone');
        $password = $this->request->param('password');

        $member = Member::where('telephone', $phone)->find();

        if (!$member) {
            return $this->json(['errno' => 1, 'msg' => '账号不存在']);
        }

        if ($member->password !== pass_hash($password, $member->salt)) {
            return $this->json(['errno' => 1, 'msg' => '密码错误']);
        }

        return $this->json([
            'errno' => 0,
            'msg' => '登录成功',
            'data' => $this->loginSuccess($member->toArray())
        ]);
    }
}
